package com.my.socket.nio.v33;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by ZhongGang
 * at 2018/8/24 15:51
 */
public class Acceptor implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Acceptor.class);

    private Selector selector;
    private Poller[] pollers;
    private AtomicInteger index = new AtomicInteger(0);

    public Acceptor(Selector selector, Poller[] pollers) throws Exception {
        this.selector = selector;
        this.pollers = pollers;
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                this.selector.select();

                Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    int length = this.pollers.length;
                    this.pollers[this.index.getAndIncrement() % length].put(socketChannel);
                    LOGGER.info("incoming socket: {}", socketChannel);
                }
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
            }
        }
    }
}
